package object_test;

import java.util.Arrays;


public class ComparableTest {
    public static void sort(Comparable[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
//                if (arr[j] > arr[j + 1]) // swap
                if (arr[j].compareTo(arr[j + 1]) > 0) {
                    // 前一个大于后一个，交换j和j + 1
                    Comparable temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    public static void main(String[] args) {
        // people是一个Person类型的数组，创建了三个Person类型的变量
        Person[] people = new Person[] {
                new Person("peter鹏",30),
                new Person("铭哥",18),
                new Person("显平",20)
        };
        sort(people);
        System.out.println(Arrays.toString(people));
    }
}

class Person implements Comparable{
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        if (this == o) {
            return 0;
        }
        if (o instanceof Person) {
            // 当前传入的o就是Person类型的引用，向下转型还原为Person
            // 要比较Person对象的大小关系，就要用到Person独有的属性，向下转型
            Person per = (Person) o;
            // 此时就是根据年龄大小比较
            return per.age - this.age;
        }
        // 报错，抛出异常
        throw new IllegalArgumentException("不是Person类型，无法比较！");
    }
}